<template>
  <div class='upload-excel'>
    <div class='btn-upload'>
      <el-button :loading='loading' type='primary' @click='handleUpload'>点击上传</el-button>
    </div>
    <input ref='excelUploadInputRef' type='file' class='excel-upload-input' accept='.xls, .xlsx' @change='handleChange'>

    <div class='drop' @drop.stop.prevent='handleDrop' @dragover.stop.prevent='handleDragover' @dragenter.stop.prevent='handleDragover'>
<!--      <i class='el-icon-upload'></i>-->
      <el-icon class='uploadIcon'><UploadFilled /></el-icon>
      <span>拖拽释放上传</span>
    </div>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { read, utils } from 'xlsx'
import { getHeaderRow, isExcel, parseExcelDate } from './utils'
import { useToast } from 'vue-toastification'

const props = defineProps({
  beforeUpload: Function,
  onSuccess: Function
})

const toast = useToast()
const loading = ref(false)
const excelUploadInputRef = ref(null)

const handleUpload = () => {
  excelUploadInputRef.value.click()
}

const handleChange = e => {
  const files = e.target.files
  const rawFile = files[0]
  if(!rawFile) return
  upload(rawFile) // 执行上传
}

const upload = rawFile => {
  console.log(rawFile)
  excelUploadInputRef.value.value = null // 将文件 input 中的 value = null

  // 调用父组件传递来的上传前回调函数，返回 true 才会继续执行
  if(props.beforeUpload){
    const flagBefore = props.beforeUpload()
    if(!flagBefore) return
  }

  uploadDo(rawFile)
}

const uploadDo = rawFile => {
  loading.value = true
  return new Promise((resolve, reject) =>{
    const reader = new FileReader()

    reader.onload = e => {
      // 1. 获取到解析后的数据
      const data = e.target.result
      // 2. 利用 XLS 对数据进行解析
      const workbook = read(data, { type: 'array'})
      // 3. 获取第一张表格名称
      const firstSheetName = workbook.SheetNames[0]
      // 4. 读取 sheet1 的数据
      const workSheet = workbook.Sheets[firstSheetName]
      // 5. 解析数据表头
      const header = getHeaderRow(workSheet)
      // 6. 解析数据体
      const results = utils.sheet_to_json(workSheet)
      // 7. 传入解析后的数据
      generateData({header, results})
      // 8. 处理 loading
      loading.value = false
      // 9. 成功回调
      resolve()
    }
    reader.readAsArrayBuffer(rawFile)
  })
}

const generateData = ({ header, results }) => {
  const records = results.map(item => {
    for(const key in item){
      if(key == '日期') {
        console.log(`转换前的日期数据：${item[key]}`)
        item[key] = parseExcelDate(item[key])// 转换日期类型的数据
        console.log(`转换后的日期数据：${item[key]}`)
      }
    }
    return item
  })
  props.onSuccess && props.onSuccess({ header, records })
}
const handleDrop = e => {
  if(loading.value) return // 正在上传则不做任何操作

  const files = e.dataTransfer.files
  if(files.length !== 1){
    toast.error('必须选择一个文件后再执行本操作！')
    return
  }

  const rawFile = files[0]
  if(!isExcel(rawFile)){
    toast.error('您只能选择类型是：xlsx,xls,csv 的文件！')
    return
  }

  uploadDo(rawFile)
}
const handleDragover = e => {
  e.dataTransfer.dropEffect = 'copy'
}

</script>
<style scoped>
.excel-upload-input {
  display: none;
  z-index: -9999;
}

.btn-upload,
.drop {
  border: 1px dashed #bbb;
  width: 350px;
  height: 160px;
  text-align: center;
  line-height: 160px;
}

.upload-excel {
    display: flex;
    justify-content: center;
    margin-top: 100px;
}

.drop {
  line-height: 60px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: #bbb;
  @apply flex items-center justify-center
}

.uploadIcon {
  font-size: 60px;
  display: block;
}
</style>